<template>
  <div>
    <!-- 面包屑模块 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="padding: 10px">
      <el-breadcrumb-item :to="{ path: '/manage/' + id }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>教学活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>试题发布</el-breadcrumb-item>
    </el-breadcrumb>
    
    <!-- 卡片视图区域 -->
    <el-card>
      <div class="publish-container">
        <div class="publish-header">
          <h3>发布试题</h3>
        </div>
        
        <!-- 流程步骤图 -->
        <div class="publish-flow">
          <el-steps :active="currentStep" finish-status="success">
            <el-step title="选择题目"></el-step>
            <el-step title="基本设置"></el-step>
            <el-step title="发布确认"></el-step>
          </el-steps>
        </div>
        
        <!-- 步骤1：选择题目 -->
        <!-- 分类选择下拉框，只在第一步（选择题目）阶段显示 -->
        <template v-if="currentStep === 1">
          <el-select 
            v-model="queryInfo.categoryId" 
            placeholder="请选择题目分类" 
            clearable 
            style="width: 300px; margin-left: 20px;" 
            @change="handleCategoryChange"
            @clear="handleCategoryClear"
          >
            <el-option
              v-for="item in questionCategories"
              :key="item.id"
              :label="item.questionCategory || item.name"
              :value="item.id">
              <div style="display: flex; justify-content: space-between; width: 100%;">
                <span style="flex: 1; overflow: hidden; text-overflow: ellipsis;">
                  {{ item.questionCategory || item.name }}
                </span>
                <el-button
                  type="text"
                  icon="el-icon-delete"
                  style="color: #f56c6c; padding: 0 0 0 10px; flex-shrink: 0;"
                  @click.stop="deleteCategory(item.id)">
                </el-button>
              </div>
            </el-option>
            <el-option class="add-category-option">
              <div style="display: flex; align-items: center; justify-content: space-between; color: #409EFF;" @click.stop="showAddCategoryDialog">
                <span>添加分类</span>
                <i class="el-icon-plus"></i>
              </div>
            </el-option>
          </el-select>
        </template>

        <!-- 添加分类对话框 -->
        <el-dialog
          title="添加题目分类"
          :visible.sync="addCategoryDialogVisible"
          width="30%">
          <el-form :model="categoryForm" :rules="categoryRules" ref="categoryForm" label-width="100px">
            <el-form-item label="分类名称" prop="name">
              <el-input v-model="categoryForm.name" placeholder="请输入分类名称" style="width: 80%;"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addCategoryDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addCategory">确 定</el-button>
          </span>
        </el-dialog>
        
        <!-- 题目类型下拉框，只在第一步（选择题目）阶段显示 -->
        <template v-if="currentStep === 1">
          <el-select v-model="queryInfo.type" placeholder="请选择题目类型" clearable style="width: 200px; margin-left: 20px;" @change="handleFilterChange">
            <el-option label="选择题" value="选择题"></el-option>
            <el-option label="填空题" value="填空题"></el-option>
            <el-option label="问答题" value="问答题"></el-option>
          </el-select>
        </template>
     
        <question-selection
          v-if="currentStep === 1"
          :questions="questions"
          :loading="loading"
          :query-info="queryInfo"
          :total="total"
          :selected-questions="selectedQuestions"
          @selection-change="handleSelectionChange"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @next="nextStep"
          @cancel="cancelPublish"
          @preview="previewQuestion">
        </question-selection>
        
        <!-- 步骤2：基本设置 -->
        <publish-settings
          v-else-if="currentStep === 2"
          :form-data="publishForm"
          :class-list="classList"
          @update:form="updatePublishForm"
          @next="nextStep"
          @prev="prevStep">
        </publish-settings>
        
        <!-- 步骤3：发布确认 -->
        <publish-confirmation
          v-else-if="currentStep === 3"
          :form-data="publishForm"
          :selected-questions="selectedQuestions"
          :class-list="classList"
          :loading="publishing"
          @prev="prevStep"
          @score-change="handleScoreChange"
          @confirm="handlePublishConfirm">
        </publish-confirmation>
      </div>
      
      <!-- 班级选择对话框 -->
      <class-selection-dialog
        :visible.sync="publish2classvisible"
        :class-list="classList"
        :selected-class-id="publishForm.classId"
        @confirm="handleClassConfirm"
        @update:visible="val => publish2classvisible = val">
      </class-selection-dialog>
    </el-card>
  </div>
</template>

<script>
import QuestionSelection from './components/QuestionSelection.vue';
import PublishSettings from './components/PublishSettings.vue';
import PublishConfirmation from './components/PublishConfirmation.vue';
import ClassSelectionDialog from './components/ClassSelectionDialog.vue';

export default {
  name: 'TeachTestPublish',
  components: {
    QuestionSelection,
    PublishSettings,
    PublishConfirmation,
    ClassSelectionDialog
  },
  created() {
    // 尝试多种方式获取教师ID
    let teacherId = null;
    
    // 1. 先从路由参数尝试获取
    if (this.$route.params.id) {
      teacherId = this.$route.params.id;
      console.log('从路由参数获取到教师ID:', teacherId);
    }
    
    // 2. 如果路由参数没有，尝试从 Vuex store 获取
    if (!teacherId && this.$store && this.$store.state && this.$store.state.userInfo) {
      teacherId = this.$store.state.userInfo.userId || this.$store.state.userInfo.id;
      console.log('从 store 获取到教师ID:', teacherId);
    }
    
    // 3. 如果仍然没有，尝试从 localStorage 获取
    if (!teacherId && localStorage.getItem('userInfo')) {
      try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        teacherId = userInfo.userId || userInfo.id; // 同时尝试两种可能的属性名
        console.log('从 localStorage 获取到教师ID:', teacherId);
      } catch (e) {
        console.error('解析 localStorage 中的 userInfo 失败:', e);
      }
    }
    
    // 4. 再尝试从 sessionStorage 获取
    if (!teacherId && sessionStorage.getItem('userInfo')) {
      try {
        const userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
        teacherId = userInfo.userId || userInfo.id;
        console.log('从 sessionStorage 获取到教师ID:', teacherId);
      } catch (e) {
        console.error('解析 sessionStorage 中的 userInfo 失败:', e);
      }
    }
    
    // 5. 如果还是没有，最后尝试全局变量
    if (!teacherId) {
      teacherId = sessionStorage.getItem('userId') || window.userId;
      console.log('从其他全局变量获取到教师ID:', teacherId);
    }
    
    if (teacherId) {
      this.id = teacherId;
      this.teacherId = teacherId;
      console.log('最终获取到教师ID:', this.teacherId);
    } else {
      // 如果仍然没有获取到教师ID，则使用临时测试ID
      this.teacherId = '300876001'; // 临时测试ID，可以根据系统实际情况调整
      this.id = this.teacherId;
      console.log('使用默认测试教师ID:', this.teacherId);
    }
    
    // 获取班级列表
    this.getClassList();
    
    // 初始化表单时间
    this.initFormTimes();
    
  
    
    // 初始化当前日期为截止时间的默认值
    const now = new Date()
    // 设置默认截止时间为当前时间加7天
    now.setDate(now.getDate() + 7)
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    this.publishForm.deadline = `${year}-${month}-${day} 23:59`
    
    this.initializeData()
  },
  
  methods: {
    async initializeData() {
    try {
      await this.getQuestionCategories()
      await this.getQuestionList()
    } catch (error) {
      console.error('初始化数据失败:', error)
      this.$message.error('初始化数据失败，请稍后重试')
    }
  },
    // 显示添加分类对话框
    showAddCategoryDialog() {
      this.categoryForm = { name: '' };
      this.$nextTick(() => {
        if (this.$refs.categoryForm) {
          this.$refs.categoryForm.clearValidate();
        }
      });
      this.addCategoryDialogVisible = true;
    },

    // 添加分类
    async addCategory() {
      try {
        const valid = await this.$refs.categoryForm.validate();
        if (!valid) return;
        
        console.log('添加分类:', this.categoryForm.name);
        // 调用API添加分类
        const response = await this.$http.post('/question-category/add', {
          questionCategory: this.categoryForm.name,
          teacherId: this.teacherId
        });
        
        console.log('添加分类响应:', response);
        
        if (response.data.code === 200) {
          this.$message.success('添加成功');
          this.addCategoryDialogVisible = false;
          this.getQuestionCategories(); // 重新加载分类列表
        } else {
          this.$message.error(response.data.msg || '添加失败');
        }
      } catch (error) {
        console.error('添加分类失败:', error);
        this.$message.error('添加失败，请重试: ' + (error.message || '未知错误'));
      }
    },

    // 删除分类
    async deleteCategory(id) {
      try {
        await this.$confirm('确定要删除该分类吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        console.log('删除分类ID:', id);
        const response = await this.$http.delete(`/question-category/delete/${id}`);
        console.log('删除分类响应:', response);
        
        if (response.data.code === 200) {
          this.$message.success('删除成功');
          this.getQuestionCategories(); // 重新加载分类列表
          // 如果当前选中的分类被删除，则清空筛选条件
          if (this.queryInfo.categoryId === id) {
            this.queryInfo.categoryId = '';
            this.handleFilterChange();
          }
        } else {
          this.$message.error(response.data.msg || '删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除分类失败:', error);
          this.$message.error('删除失败，请重试: ' + (error.message || '未知错误'));
        }
      }
    },

    // 获取题目分类列表
    async getQuestionCategories() {
      try {
        console.log('开始获取题目分类...');
        const response = await this.$http.get('/question-category/list');
        console.log('获取题目分类响应:', response);
        
        if (response.data.code === 200) {
          this.questionCategories = response.data.data || [];
          if (this.questionCategories.length > 0) {
            this.queryInfo.categoryId = this.questionCategories[0].id;
          }
          console.log('成功获取题目分类:', this.questionCategories);
        } else {
          console.error('获取题目分类失败:', response.data.msg);
          this.$message.error('获取题目分类失败: ' + (response.data.msg || '未知错误'));
        }
      } catch (error) {
        console.error('获取题目分类异常:', error);
        this.$message.error('获取题目分类异常: ' + (error.message || '未知错误'));
      }
    },

    // 处理分类选择变化
    handleCategoryChange(categoryId) {
      console.log('分类选择变化:', categoryId);
      this.queryInfo.pageNum = 1; // 重置为第一页
      this.getQuestionList(); // 重新加载题目列表
    },
    
    // 处理清空分类筛选
    handleCategoryClear() {
      console.log('清空分类筛选');
      this.queryInfo.pageNum = 1; // 重置为第一页
      this.getQuestionList(); // 重新加载题目列表
    },
    
    // 筛选条件变化处理（保留给其他筛选条件使用）
    handleFilterChange() {
      this.queryInfo.pageNum = 1; // 重置为第一页
      this.getQuestionList(); // 重新加载题目列表
    },

    // 更新发布表单数据
    updatePublishForm(updatedForm) {
      this.publishForm = { ...this.publishForm, ...updatedForm };
    },
    
    // 处理题目选择变化
    handleSelectionChange(selectedQuestions) {
      console.log('题目选择变化:', selectedQuestions);
      this.selectedQuestions = selectedQuestions || [];
      console.log('当前选中题目数量:', this.selectedQuestions.length);
    },
    
    // 处理班级确认
    handleClassConfirm(classId) {
      this.publishForm.classId = classId;
      this.publish2classvisible = false;
    },
    
    // 处理题目分值变更
    handleScoreChange(question) {
      console.log('题目分值已更新:', question.id, question.maxScore);
      // 在selectedQuestions中更新对应题目的maxScore
      const index = this.selectedQuestions.findIndex(q => q.id === question.id);
      if (index !== -1) {
        this.$set(this.selectedQuestions[index], 'maxScore', question.maxScore);
      }
    },
    
    // 处理发布确认
    handlePublishConfirm(questionsWithScores) {
      if (questionsWithScores && Array.isArray(questionsWithScores)) {
        // 更新题目分值
        questionsWithScores.forEach(item => {
          const index = this.selectedQuestions.findIndex(q => q.id === item.id);
          if (index !== -1) {
            this.$set(this.selectedQuestions[index], 'maxScore', item.maxScore);
          }
        });
      }
      this.finalPublish();
    },
    
    // 处理开始方式变化
    handleStartModeChange(val) {
      if (val === 'immediate') {
        // 立即开始，设置开始时间为当前时间
        const now = new Date();
        this.publishForm.startTime = this.formatDateTime(now);
        this.calculateDeadline();
      } else if (val === 'scheduled') {
        // 定时开始，清空开始时间
        this.publishForm.startTime = '';
        this.publishForm.deadline = '';
      } else if (val === 'manual') {
        // 点击开始，清空开始时间和截止时间
        this.publishForm.startTime = '';
        this.publishForm.deadline = '';
      }
    },
    
    // 处理开始时间变化
    handleStartTimeChange() {
      console.log('开始时间变化:', this.publishForm.startTime);
      if (this.publishForm.startTime && this.publishForm.timeLimit) {
        this.calculateDeadline();
      } else if (this.publishForm.deadline && new Date(this.publishForm.startTime) >= new Date(this.publishForm.deadline)) {
        // 如果没有设置答题时间，且开始时间晚于或等于截止时间，则清空截止时间
        this.publishForm.deadline = '';
      }
    },
    
    // 处理答题时间变化
    handleTimeLimitChange() {
      console.log('答题时间变化:', this.publishForm.timeLimit);
      if (this.publishForm.startTime && this.publishForm.timeLimit) {
        this.calculateDeadline();
      }
    },
    
    // 获取题库数据
    getQuestionList() {
      this.loading = true;
      
      // 确保有teacherId
      if (!this.teacherId) {
        // 尝试多种方式获取教师ID
        let teacherId = null;
        
        // 1. 从路由参数获取
        if (this.$route.params.id) {
          teacherId = this.$route.params.id;
        }
        
        // 2. 从 store 获取
        if (!teacherId && this.$store && this.$store.state && this.$store.state.userInfo) {
          teacherId = this.$store.state.userInfo.userId || this.$store.state.userInfo.id;
        }
        
        // 3. 从 localStorage 获取
        if (!teacherId) {
          try {
            const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
            teacherId = userInfo.userId || userInfo.id;
          } catch (e) {
            console.error('解析 localStorage 中的 userInfo 失败:', e);
          }
        }
        
        // 4. 从 sessionStorage 获取
        if (!teacherId) {
          try {
            const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');
            teacherId = userInfo.userId || userInfo.id;
          } catch (e) {
            console.error('解析 sessionStorage 中的 userInfo 失败:', e);
          }
        }
        
        // 5. 尝试全局变量
        if (!teacherId) {
          teacherId = sessionStorage.getItem('userId') || window.userId;
        }
        
        // 如果找到了有效ID
        if (teacherId) {
          this.teacherId = teacherId;
          console.log('从多种方式找到教师ID:', teacherId);
        } else {
          // 使用默认测试ID
          this.teacherId = '300876001';
          console.log('使用默认测试教师ID:', this.teacherId);
        }
      }
      
      console.log('当前教师ID:', this.teacherId);
      
      // 构建请求参数
      const params = {
        pageNum: this.queryInfo.pageNum,
        pageSize: this.queryInfo.pageSize,
        teacherId: this.teacherId
      };
      
      // 添加可选参数
      if (this.queryInfo.type && this.queryInfo.type !== '') {
        params.type = this.queryInfo.type;
      }
      
      if (this.queryInfo.keyword && this.queryInfo.keyword !== '') {
        params.keyword = this.queryInfo.keyword;
      }
      
      if (this.queryInfo.categoryId && this.queryInfo.categoryId !== '') {
        params.categoryId = this.queryInfo.categoryId;
      }
      
      console.log('请求参数:', params);
      
      // 添加调试日志，记录请求参数
      console.log('正在发送题库请求，参数:', JSON.stringify(params));
      
      // 使用带超时的请求
      return this.$http.get('/question/list', { 
        params,
        timeout: 10000 // 设置10秒超时
      })
        .then(res => {
          console.log('数据返回成功:', res);
          
          if (res.data.code !== 200) {
            this.$message.error('获取题库数据失败: ' + (res.data.msg || '未知错误'));
            return Promise.reject(res.data.msg || '服务器错误');
          }
          
          // 获取响应数据
          const responseData = res.data.data;
          
          // 更新状态
          this.questions = responseData.items || [];
          this.total = responseData.total || 0;
          
          // 初始化选中状态
          this.questions.forEach(question => {
            this.$set(question, 'selected', false);
          });
          
          return responseData;
        })
        .catch(error => {
          console.error('获取题库失败:', error);
          this.$message.error('获取题库失败: ' + (error.message || '网络错误'));
          return Promise.reject(error);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 下一步
    nextStep() {
      // 第一步（选择题目）的验证
      if (this.currentStep === 1) {
        if (!this.selectedQuestions || this.selectedQuestions.length === 0) {
          this.$message.warning('请至少选择一道题目');
          return;
        }
        console.log('已选中题目数量:', this.selectedQuestions.length);
      }
      // 第二步（基本设置）的表单验证
      else if (this.currentStep === 2) {
        if (!this.publishForm.classId) {
          this.$message.warning('请选择班级');
          return;
        }
        if (!this.validateForm()) {
          return;
        }
      }
      
      // 如果当前不是最后一步，才进入下一步
      if (this.currentStep < 4) {
        this.currentStep += 1;
      }
    },
    
    // 验证表单
    validateForm() {
      // if (!this.publishForm.title) {
      //   this.$message.warning('请填写标题');
      //   return false;
      // }
      
      if (this.publishForm.startMode === 'scheduled' && !this.publishForm.startTime) {
        this.$message.warning('请设置开始时间');
        return false;
      }
      
      if (!this.publishForm.deadline) {
        this.$message.warning('请设置截止时间');
        return false;
      }
      
      if (this.publishForm.startMode === 'scheduled' && this.publishForm.startTime) {
        const startTime = new Date(this.publishForm.startTime).getTime();
        const deadline = new Date(this.publishForm.deadline).getTime();
        if (startTime >= deadline) {
          this.$message.warning('开始时间必须早于截止时间');
          return false;
        }
      }
      
      return true;
    },
    
    // 上一步
    prevStep() {
      if (this.currentStep > 1) {
        this.currentStep -= 1;
      } else {
        // 如果是第一步，返回到上一页
        this.cancelPublish();
      }
    },
    
    // 获取班级列表
    getClassList() {
      this.$http.get('/class/findByTeacher', {
        params: {
          teacherId: this.teacherId
        }
      }).then(({ data: res }) => {
        if (res.code === 200) {
          console.log(res.data)
          this.classList = res.data
        } else {
          console.error('获取班级列表失败:', res)
          this.$message.error('获取班级列表失败: ' + (res.msg || '未知错误'))
        }
      }).catch(error => {
        console.error('获取班级列表请求失败:', error)
        this.$message.error('获取班级列表请求失败: ' + (error.message || '未知错误'))
      })
    },
    
    // 初始化表单时间
    initFormTimes() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      
      // 设置默认开始时间为当前时间+5分钟
      const startTime = new Date(now.getTime() + 5 * 60 * 1000);
      const startHours = String(startTime.getHours()).padStart(2, '0');
      const startMinutes = String(startTime.getMinutes()).padStart(2, '0');
      
      this.publishForm.startTime = `${year}-${month}-${day} ${startHours}:${startMinutes}`;
      
      // 设置默认截止时间为明天同一时间
      const tomorrow = new Date(now);
      tomorrow.setDate(tomorrow.getDate() + 1);
      const tomorrowStr = `${tomorrow.getFullYear()}-${String(tomorrow.getMonth() + 1).padStart(2, '0')}-${String(tomorrow.getDate()).padStart(2, '0')} ${hours}:${minutes}`;
      
      this.publishForm.deadline = tomorrowStr;
    },
    
    // 计算截止时间
    calculateDeadline() {
      console.log('计算截止时间 - 开始模式:', this.publishForm.startMode);
      console.log('当前开始时间:', this.publishForm.startTime);
      console.log('当前答题时长:', this.publishForm.timeLimit);
      
      let startTime;
      
      // 根据不同的开始模式确定开始时间
      if (this.publishForm.startMode === 'immediate') {
        // 立即开始模式，使用当前时间
        startTime = new Date();
      } else if (this.publishForm.startMode === 'scheduled' && this.publishForm.startTime) {
        // 定时开始模式，使用用户设置的开始时间
        startTime = new Date(this.publishForm.startTime);
      } else {
        console.log('无法计算截止时间：未设置开始时间或开始模式不支持');
        return;
      }
      
      // 创建截止时间对象
      let deadline = new Date(startTime);
      
      // 如果设置了时间限制，则根据时间限制计算截止时间
      if (this.publishForm.timeLimit && this.publishForm.timeLimit > 0) {
        deadline = new Date(startTime.getTime() + this.publishForm.timeLimit * 60 * 1000);
        console.log('根据答题时长计算截止时间:', deadline);
      } 
      // 否则默认为24小时后
      else {
        deadline.setHours(deadline.getHours() + 24);
        console.log('使用默认24小时截止时间:', deadline);
      }
      
      // 格式化日期时间
      const year = deadline.getFullYear();
      const month = String(deadline.getMonth() + 1).padStart(2, '0');
      const day = String(deadline.getDate()).padStart(2, '0');
      const hours = String(deadline.getHours()).padStart(2, '0');
      const minutes = String(deadline.getMinutes()).padStart(2, '0');
      
      const formattedDeadline = `${year}-${month}-${day} ${hours}:${minutes}`;
      console.log('最终截止时间:', formattedDeadline);
      
      this.publishForm.deadline = formattedDeadline;
    },
    
    // 搜索题目
    async searchQuestions() {
      this.loading = true;
      
      // 直接调用 getQuestionList，因为搜索和获取列表的逻辑已经统一
      await this.getQuestionList();
      
      if (this.questions.length === 0) {
        this.$message.info('未找到相关题目');
      }
    },
    
    // 清空搜索
    clearSearch() {
      this.searchQuery = '';
      // 清空搜索后重新加载题目列表，已选状态会通过 getQuestionList 自动保持
      this.getQuestionList();
    },
    
    // 获取题目列表
    async getQuestionList() {
      this.loading = true;
      try {
        const response = await this.$http.get('/question/list', {
          params: {
            page: this.queryInfo.pageNum || 1,
            pageSize: this.queryInfo.pageSize || 100,
            status: 1, // 只查询已启用的题目
            keyword: this.searchQuery || undefined,
            categoryId: this.queryInfo.categoryId || undefined,
            type: this.queryInfo.type || undefined
          }
        });
        
        console.log('获取题目列表响应:', response.data);
        
        if (response.data.code === 200) {
          // 注意：这里直接使用response.data.data，因为数据在data字段中
          const responseData = response.data.data || {};
          const questionItems = responseData.items || [];
          
          // 更新总数
          this.total = responseData.total || 0;
          
          // 创建已选题目ID的映射，用于快速查找
          const selectedQuestionIds = new Set((this.selectedQuestions || []).map(q => q.id));
          
          // 更新题目列表，保持已选状态
          this.questions = questionItems.map(question => ({
            ...question,
            selected: selectedQuestionIds.has(question.id)
          }));
          
          console.log('处理后的题目列表:', this.questions);
        } else {
          this.$message.error(response.data.msg || '获取题目列表失败');
        }
      } catch (error) {
        console.error('获取题目列表失败:', error);
        this.$message.error('获取题目列表失败: ' + (error.message || '未知错误'));
      } finally {
        this.loading = false;
      }
    },
    
    // 处理题目点击事件
    handleQuestionClick(event, question) {
      // 阻止事件冒泡和默认行为
      event.preventDefault();
      event.stopPropagation();
      
      // 使用 requestAnimationFrame 确保在下一帧处理
      // 这样可以让 UI 更流畅响应
      requestAnimationFrame(() => {
        this.toggleQuestionSelection(question);
      });
    },
    
    // 切换题目选中状态
    toggleQuestionSelection(question) {
      // 使用 Vue.set 确保响应式更新
      const index = this.selectedQuestions.findIndex(q => q.id === question.id);
      
      if (index > -1) {
        // 如果题目已选中，则移除
        this.$delete(this.selectedQuestions, index);
        this.$set(question, 'selected', false);
      } else {
        // 如果题目未选中，则添加
        // 创建新对象避免引用问题
        const questionCopy = {...question, selected: true};
        this.selectedQuestions.push(questionCopy);
        this.$set(question, 'selected', true);
      }
      
      // 触发视图更新（如果需要）
      this.$nextTick(() => {
        // 确保 DOM 更新完成
      });
    },
    
    // 尝试直接通过教师ID查询题目
    tryDirectTeacherQuery() {
      if (!this.teacherId) {
        console.error('无法执行直接查询：没有教师ID');
        return Promise.reject('无教师ID');
      }
      
      return this.$http.get('/question/list', {
        params: {
          teacherId: this.teacherId,
          pageNum: 1,
          pageSize: 50
        },
        timeout: 10000
      }).then(res => {
        if (res.data.code === 200) {
          console.log('直接查询教师题目结果:', res.data.data);
          
          // 处理返回数据
          const data = res.data.data;
          if (data.items || data.list) {
            this.questions = (data.items || data.list).map(item => ({
              ...item, 
              selected: false
            }));
            this.total = data.total || this.questions.length;
          } else if (Array.isArray(data)) {
            this.questions = data.map(item => ({
              ...item,
              selected: false
            }));
            this.total = data.length;
          } else {
            console.warn('未识别的直接查询返回格式');
            this.questions = [];
            this.total = 0;
          }
          
          return this.questions;
        } else {
          console.error('直接查询教师题目失败:', res.data);
          return Promise.reject(res.data.msg || '查询失败');
        }
      }).catch(err => {
        console.error('直接查询教师题目请求错误:', err);
        return Promise.reject(err);
      });
    },
    
    // 获取完整图片URL
    getFullImageUrl(url) {
      if (!url) return '';
      
      // 如果url已经是完整的地址（以http开头），则直接返回
      if (url.startsWith('http')) {
        return url;
      }
      
      // 否则添加基础URL
      return 'http://localhost:4041' + (url.startsWith('/') ? url : '/' + url);
    },
    
    // 分页功能
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getQuestionList();
    },
    
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage;
      this.getQuestionList();
    },
    
    // 保存为草稿
    saveAsDraft() {
      if (!this.publishForm.title) {
        this.$message.warning('请填写标题');
        return;
      }
      
      const draftData = {
        ...this.publishForm,
        selectedQuestions: this.questions.filter(q => q.selected).map(q => q.id),
        saveTime: new Date().toLocaleString(),
        id: Date.now().toString() // 使用时间戳作为草稿ID
      };
      
      // 从本地存储获取现有草稿
      let drafts = JSON.parse(localStorage.getItem('examDrafts') || '[]');
      // 添加新草稿
      drafts.unshift(draftData);
      // 保存到本地存储
      localStorage.setItem('examDrafts', JSON.stringify(drafts));
      
      this.$message.success('已保存到草稿箱');
    },
    
    // 确认发布对话框
    confirmPublish() {
      if (this.questions.filter(q => q.selected).length === 0) {
        this.$message.warning('请至少选择一道题目');
        return;
      }
      
      if (!this.validateForm()) {
        return;
      }
      
      this.publishDialogVisible = true;
    },
    
    // 取消发布
    cancelPublish() {
      this.$router.go(-1) // 返回上一页
    },
    
    // 发布题目 - 在确认发布对话框点击确定后调用
    publishQuestions() {
      // 先关闭确认发布对话框
      this.publishDialogVisible = false;
      
      // 收集选中的题目
      this.publishForm.questionIds = this.questions
        .filter(q => q.selected)
        .map(q => q.id);
      
      // 直接发布，不再显示选择班级对话框
      this.finalPublish();
    },
    
    // 班级选择变化处理
    handleClassChange(classId) {
      console.log('选中班级:', classId);
      this.publishForm.classId = classId;
      
      // 获取班级名称
      const selectedClass = this.classList.find(c => c.classId === classId);
      if (selectedClass) {
        this.selectedClassName = selectedClass.className;
      }
    },
    
    // 最终发布到班级
    finalPublish() {
      if (!this.publishForm.classId) {
        this.$message.warning('请选择班级');
        return;
      }
      
      // 获取选中的班级名称
      const selectedClass = this.classList.find(c => c.classId === this.publishForm.classId);
      if (selectedClass) {
        this.selectedClassName = selectedClass.className;
      }
      
      this.publishing = true;
      
      // 收集选中的题目 ID
      console.log('发布时选中的题目:', this.selectedQuestions);
      const questionIds = this.selectedQuestions.map(q => q.id);
      
      // 准备要发送给后端的数据
      const requestData = {
        questionIds: questionIds.map(id => parseInt(id)), // 确保题目ID是数字
        classId: parseInt(this.publishForm.classId), // 转换为整数
        publishType: this.publishForm.answerType, // 课中、课后或测试
        teacherId: parseInt(this.teacherId), // 转换为整数
        title: this.publishForm.title, // 添加测试名称字段
        examName: this.publishForm.title, // 添加 examName 字段，使用标题作为考试名称
        startTime: this.publishForm.startTime,
        endTime: this.publishForm.deadline,
        answerTime: parseInt(this.publishForm.timeLimit)*60*1000, // 转换为整数
        // 添加每道题目的分值信息
        questionScores: this.selectedQuestions.map(q => ({
          questionId: parseInt(q.id),
          maxScore: q.maxScore || q.score || 5 // 使用设置的maxScore，如果没有则使用原始分值
        }))
      };
      
      console.log('发送数据:', requestData); // 添加日志查看数据类型
      
      // 保存到本地存储（用于前端测试）
      try {
        // 添加前端显示所需的额外字段
        const localStorageData = {
          ...requestData,
          status: 'published',
          publishTime: new Date().toISOString(),
          id: Date.now().toString(),
          selectedQuestions: questionIds,
          className: this.selectedClassName
        };
        
        let publishedTests = JSON.parse(localStorage.getItem('publishedTests') || '[]');
        publishedTests.unshift(localStorageData);
        localStorage.setItem('publishedTests', JSON.stringify(publishedTests));
        
        // 从草稿箱中移除
        let drafts = JSON.parse(localStorage.getItem('examDrafts') || '[]');
        const updatedDrafts = drafts.filter(draft => draft.title !== this.publishForm.title);
        localStorage.setItem('examDrafts', JSON.stringify(updatedDrafts));
      } catch (err) {
        console.error('保存到本地存储错误:', err);
      }
      
      // 打印请求数据
      console.log('准备发送到后端的请求数据:', JSON.stringify(requestData, null, 2));
      
      // 发送请求到后端
      this.$http.post('/question/publish', requestData)
        .then(res => {
          if (res.data.code === 200) {
            this.$message.success('发布成功: ' + res.data.msg);
            // 关闭对话框
            this.publish2classvisible = false;
            // 跳转到我的发布页面
            setTimeout(() => {
              // 获取当前用户ID
              const userId = this.$route.params.id || sessionStorage.getItem('teacherId');
              this.$router.push(`/manage/${userId}/teach/myPublish`);
            }, 500);
          } else {
            this.$message.error(res.data.msg || '发布失败');
          }
        })
        .catch(err => {
          console.error('发布错误:', err);
          this.$message.error('发布请求异常，请重试');
        })
        .finally(() => {
          this.publishing = false;
        });
    }
  },
  
  watch: {
    // 监听发布表单变化，自动计算截止时间
    'publishForm.timeLimit': function(val) {
      this.calculateDeadline();
    },
    'publishForm.startTime': function(val) {
      this.calculateDeadline();
    }
  },

  
  data() {
    // 初始化基本日期
    const now = new Date();
    
    return {
      id: null,
      teacherId: null,
      confirmDialogVisible: false,
      classList: [], // 班级列表数据
      selectedClass: '', // 选中的班级ID
      selectedClassName: '', // 选中的班级名称
      currentStep: 1, // 当前步骤：1-基本设置，2-选择试题，3-选择班级，4-发布确认
      selectedQuestions: [], // 存储已选中的题目对象
      publishForm: {
        title: '',
        answerType: '课中', // 新增：答题类型，直接使用中文值：课中、课后、测试
        startMode: 'immediate', // 新增：开始方式，immediate-立即开始，scheduled-定时开始，manual-点击开始
        publishTimeType: 'now',
        attemptTimes: '1',
        startTime: '', // 开始时间
        deadline: '', // 截止时间，将通过计算生成
        timeLimit: 60, // 默认时长60分钟
        timeoutAction: 'autoSubmit', // 新增：超时处理，autoSubmit-自动提交，keepWork-保留作答
        // 移除结果设置
        notifyBeforeDeadline: false, // 新增：截止前提醒
        notifyWhenPublish: true, // 新增：发布时通知
        wechatReminder: false,
        publishType: 'homework',
        questionIds: [],
        classId: '',
        status: 'draft' // draft-草稿, published-已发布
      },
      publishTypeOptions: [
        { value: 'homework', label: '作业' },
        { value: 'quiz', label: '测验' },
        { value: 'exam', label: '考试' }
      ],
      // 发布确认对话框
      publishDialogVisible: false,
      // 当前步骤
      currentStep: 1,
      publishing: false,
      // 时间选择器选项
      startTimeOptions: {
        disabledDate: (time) => {
          return time.getTime() < Date.now() - 8.64e7; // 不能选择今天之前的日期
        }
      },
      deadlineOptions: {
        disabledDate: (time) => {
          if (!this.publishForm.startTime) return true;
          const startTime = new Date(this.publishForm.startTime).getTime();
          return time.getTime() < startTime;
        }
      },
      // 试题查询相关
      queryInfo: {
        pageNum: 1,
        pageSize: 10,
        keyword: '',
        type: '',
        categoryId: ''  // 确保有categoryId字段
      },
      total: 0,
      questions: [],
      searchQuery: '',
      searchTimer: null,
      loading: false,
      publish2classvisible: false,
      classList: [],
      selectedClass: null,
      
      // 题目分类相关
      questionCategories: [], // 题目分类列表
      addCategoryDialogVisible: false, // 添加分类对话框显示状态
      categoryForm: {
        name: '' // 分类名称
      },
      categoryRules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  // 已合并created钩子，避免重复
  
  mounted() {
    // 初始化当前日期为截止时间的默认值
    const now = new Date()
    // 设置默认截止时间为当前时间加7天
    now.setDate(now.getDate() + 7)
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    this.publishForm.deadline = `${year}-${month}-${day} 23:59`
  },
  computed: {
    // 获取已选题目数量
    selectedQuestionsCount() {
      return this.questions.filter(q => q.selected).length;
    },
    // 获取选中的班级名称
    selectedClassName() {
      if (!this.selectedClass) return '';
      const classItem = this.classList.find(item => item.classId === this.selectedClass);
      return classItem ? classItem.className : '';
    }
  }
}
</script>

<style scoped>
.publish-container {
  padding: 20px;
}

.publish-header {
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.publish-header h3 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.publish-flow {
  margin-bottom: 30px;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.section-indicator {
  width: 4px;
  height: 16px;
  background-color: #409EFF;
  margin-right: 10px;
  border-radius: 2px;
}

.section-header h4 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .publish-container {
    padding: 15px;
  }
  
  .publish-header h3 {
    font-size: 18px;
  }
  
  .section-header h4 {
    font-size: 15px;
  }
}
/* 必填标记 */
.required-mark {
  color: #F56C6C;
  margin-left: 4px;
}

.tip-text {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.tip-text i {
  margin-right: 4px;
  color: #67C23A;
}
/* 整体布局样式 */
.publish-flow {
  margin: 20px 0 30px;
}

.publish-container {
  padding: 20px 0;
}

.publish-header {
  margin-bottom: 25px;
  text-align: center;
}

.publish-header h3 {
  font-size: 22px;
  color: #409EFF;
  margin: 0;
  font-weight: 500;
}

.divider {
  position: relative;
  height: 20px;
  text-align: center;
  margin: 30px 0;
}

.divider:before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: #EBEEF5;
  z-index: 1;
}

.divider span {
  position: relative;
  z-index: 2;
  padding: 0 20px;
  background: white;
  font-size: 16px;
  color: #909399;
}

/* 思维导图样式 */
.mind-map-container {
  position: relative;
  height: 350px;
  margin: 20px 0 40px;
}

.center-node {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 180px;
  height: 80px;
  background: #409EFF;
  color: white;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.center-node .node-content {
  text-align: center;
  font-size: 16px;
  font-weight: 500;
  padding: 0 10px;
}

.center-node i {
  font-size: 24px;
  margin-bottom: 5px;
  display: block;
}

.radiating-lines .line {
  position: absolute;
  background: #E6A23C;
  height: 2px;
  z-index: 1;
}

.line-left-top {
  width: 120px;
  top: 30%;
  left: 25%;
  transform: rotate(-30deg);
}

.line-left {
  width: 120px;
  top: 50%;
  left: 25%;
}

.line-left-bottom {
  width: 120px;
  top: 70%;
  left: 25%;
  transform: rotate(30deg);
}

.line-right-top {
  width: 120px;
  top: 30%;
  right: 25%;
  transform: rotate(30deg);
}

.line-right {
  width: 120px;
  top: 50%;
  right: 25%;
}

.line-right-bottom {
  width: 120px;
  top: 70%;
  right: 25%;
  transform: rotate(-30deg);
}

.node {
  position: absolute;
  width: 160px;
  padding: 12px;
  background: white;
  border-radius: 6px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  z-index: 2;
  cursor: pointer;
  transition: all 0.3s;
  border-left: 3px solid #E6A23C;
}

.node:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
}

.node-left-top {
  top: 20%;
  left: 10%;
}

.node-left {
  top: 45%;
  left: 5%;
}

.node-left-bottom {
  top: 70%;
  left: 10%;
}

.node-right-top {
  top: 20%;
  right: 10%;
}

.node-right {
  top: 45%;
  right: 5%;
}

.node-right-bottom {
  top: 70%;
  right: 10%;
}

.node .node-content {
  font-size: 14px;
  color: #606266;
}

.node .node-content i {
  margin-right: 5px;
  color: #E6A23C;
}

/* 设置面板样式 */
.time-setting-panel,
.notification-setting-panel {
  margin-top: 25px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #409EFF;
}

.time-setting-header,
.result-setting-header {
  font-size: 16px;
  font-weight: 500;
  color: #409EFF;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #EBEEF5;
}

.type-selector {
  margin: 10px 0 20px;
}

.duration-input {
  display: flex;
  align-items: center;
}

.duration-unit {
  margin: 0 10px;
  color: #606266;
}

.help-icon {
  color: #909399;
  cursor: help;
}

.deadline-note {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.deadline-note i {
  margin-right: 4px;
  color: #E6A23C;
}

/* 表单元素样式 */
.publish-summary {
  padding: 0 10px;
}

.publish-summary h4 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #303133;
  font-weight: 500;
}

.publish-tips {
  margin-top: 15px;
  padding: 10px;
  background-color: #f4f4f5;
  border-radius: 4px;
  color: #909399;
  font-size: 13px;
}

.publish-tips i {
  margin-right: 5px;
  color: #e6a23c;
}

.publish-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.action-right {
  display: flex;
  gap: 10px;
}

.step-actions {
  margin-top: 30px;
  text-align: center;
}

.form-row {
  display: flex;
  margin-bottom: 18px;
  gap: 20px;
}

.form-item {
  flex: 1;
}

.form-label {
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

.form-input {
  width: 100%;
}
.publish-container {
  padding: 20px;
}

.publish-header {
  margin-bottom: 30px;
}

.publish-header h3 {
  font-size: 20px;
  font-weight: 500;
  color: #303133;
  margin: 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #EBEEF5;
}

.publish-settings-section,
.select-questions-section {
  margin-bottom: 30px;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.section-indicator {
  width: 4px;
  height: 16px;
  background-color: #409EFF;
  margin-right: 8px;
  border-radius: 2px;
}

.section-header h4 {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 0;
}

.settings-form {
  padding: 0 20px;
}

.form-item {
  margin-bottom: 20px;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.form-row .form-item {
  flex: 1;
  margin-bottom: 0;
}

.form-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.form-input {
  width: 100%;
}

.form-input .el-input,
.form-input .el-select,
.form-input .el-date-picker {
  width: 100%;
}

.radio-group {
  display: flex;
  align-items: center;
}

.radio-group .el-radio {
  margin-right: 30px;
}

.radio-group .el-radio:last-child {
  margin-right: 0;
}

.publish-actions,
.step-actions {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #EBEEF5;
  margin-top: 20px;
}

.publish-actions .el-button,
.step-actions .el-button {
  min-width: 100px;
  margin: 0 10px;
}

/* 搜索区域样式 */
.search-container {
  margin-bottom: 20px;
  padding: 0 20px;
}

/* 题目列表样式 */
.questions-list {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  padding: 15px;
  margin: 0 20px 20px;
  background-color: #f9f9f9;
}

.question-items {
  max-height: 500px;
  overflow-y: auto;
  margin-bottom: 20px;
}

.question-item {
  padding: 15px;
  margin-bottom: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  transition: all 0.3s;
  cursor: pointer;
}

.question-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.question-content {
  display: flex;
  flex-direction: column;
  transition: all 0.3s;
  padding: 8px;
  border-radius: 4px;
}

.question-content.selected {
  background-color: #f0f7ff;
  border-left: 3px solid #409EFF;
  margin-left: -3px;
}

.question-checkbox {
  display: flex;
  align-items: center;
  cursor: pointer;
  user-select: none;
  padding: 8px 0;
  
  i {
    margin-right: 8px;
    font-size: 16px;
    color: #dcdfe6;
    transition: color 0.2s;
  }
  
  .question-title {
    flex: 1;
    margin: 0;
    line-height: 1.5;
  }
  
  &:hover i {
    color: #c0c4cc;
  }
}

.question-content {
  &.selected {
    .question-checkbox i {
      color: #409EFF;
    }
    
    .question-title {
      color: #409EFF;
    }
  }
  
  &:hover {
    background-color: #f5f7fa;
  }
}

.question-checkbox >>> .el-checkbox__label {
  width: 100%;
  white-space: normal;
}

.question-title {
  font-size: 14px;
  color: #303133;
  line-height: 1.5;
  margin-left: 8px;
}

.question-image {
  margin-top: 10px;
  max-width: 100%;
}

.question-image img {
  max-width: 300px;
  max-height: 200px;
  border-radius: 4px;
  border: 1px solid #EBEEF5;
  object-fit: contain;
}

.text-center {
  text-align: center;
  padding: 40px 0;
}

.loading-text,
.empty-result p {
  margin-top: 10px;
  color: #909399;
  font-size: 14px;
}

.el-icon-loading,
.el-icon-warning-outline {
  font-size: 24px;
  color: #909399;
}
</style>
